package com.ju.ushop.product.exception;

import com.ju.common.constant.BizCodeEnum;
import com.ju.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author GuoJun
 * @date 2021/6/3 23:25
 * @email 864350301@qq.com
 */
@Slf4j
@RestControllerAdvice
public class BizControllerAdvice {


    /**
     * 参数效验异常
     * @param exception
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R exception(MethodArgumentNotValidException exception){
        BindingResult bindingResult = exception.getBindingResult();
        Map<String, String > errors = new HashMap<>(16);
        bindingResult.getFieldErrors().forEach(e -> {
            errors.put(e.getField(),e.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",errors);
    }

    @ExceptionHandler(value = Throwable.class)
    public R exception(Throwable throwable){
        log.error("错误:",throwable);
        return R.error(BizCodeEnum.UN_KNOW_EXCEPTION.getCode(),BizCodeEnum.UN_KNOW_EXCEPTION.getMsg());
    }
}
